<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\Sms;
use addons\epay\library\Service;
use Exception;
use think\Validate;
use app\api\controller\Index;

/**
 * app---首页
 */
class Home extends Api
{
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];



	/**
	 * @ApiTitle    (app---首页)
	 * @ApiSummary  (app---首页)
	 * @ApiMethod   (POST)
	 * @ApiRoute    (api/Home/index)
	 * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams   (name="hot_type", type="varchar", required=false, description="mobile:手游  network:端游")
	 * @ApiParams   (name="game_id", type="varchar", required=false, description="游戏id")
	 * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "ok",
	"time": "1635241250",
	"data": {
	"user": [
	{
	用户
	"id": 1,
	"nickname": "昵称",
	},
	],
	"hotGame": [
	热门游戏
	{
	"id": 2,
	"game": "游戏名",
	"image": "/uploads/20211014/4d2542db5824e0ae2006dbe090240be6.jpg",
	"type": "mobile:手游  network:端游",
	}
	],
	"ad": [
	{
	轮播图
	"id": 1,
	"image": "/uploads/20211013/6aecb7e605e2d3fca33d807306643f02.jpg",
	},
	],
	"game": [
	{
	所有游戏
	"id": 1,
	"game": "游戏名",
	},
	],
	"goods": [
	{
	展示商品
	"id": 1,
	"is_safe": "账号安全服务1终身包赔2不服务3心意购",
	"title": "标题",
	"area": "区",
	"server": "服",
	"cross": "跨区 ---  地下城专属,
	"price": "价格",
	"image": "图片",
	},
	],
       "order": [
    {
    成交记录
    "id": 1,
    "account": "账号",
    "game": "游戏",
    "title": "标题",
    },
    ],
	 * })
	 */
	public function index()
	{
		$token = $this->request->header('token');
		// 用户登录
		if (!empty($token)) {
			$res['user'] = Db::name('personal')->field('id,nickname')->where('token',$token)->find();
		}
		// 热门游戏
		$hot['is_hot'] = 1;
		$hot['status'] = 'normal';
		$hotType = $this->request->post('hot_type');
		if (!empty($hotType)) {
			$hot['type'] = $hotType;
		}
		$hotGame = Db::name('game')->field('id,game,type,image,is_hot')->where($hot)->select();
		foreach ($hotGame as $k=>$v) {
			$hotGame[$k]['image'] = config('api_image_url') . $v['image'];
		}
		// 广告位banner
		$ad = Db::name('ad')
			->field('id,aid,image,title,type')
			->where('aid',4)
			->where('status','normal')
			->select();
		foreach ($ad as $k=>$v) {
			$ad[$k]['image'] = config('api_image_url') . $v['image'];
		}
		// 公告
		$article = Db::name('help')
			->field('id,title')
			->where('status','normal')
			->order('createtime desc')
			->limit(8)
			->select();
		// 热门推荐
		$popular = Db::name('game')
			->field('id,game,type,w_image,is_hot')
			->where('status','normal')
			->orderRaw('Rand()')
			->limit(5)
			->select();
		foreach ($popular as $k=>$v) {
			$popular[$k]['info'] = Db::name('game_info')->field('id,name')->where('game_id',$v['id'])->where('gt_id',5)->where('status','normal')->find();
			$popular[$k]['w_image'] = config('api_image_url') . $v['w_image'];
		}
		// 游戏
		$game = Db::name('game')->field('id,game')->where('status','normal')->select();
		foreach ($game as $k=>$v) {
			$map['stock'] = ['gt',0];
			$map['gameid'] = $v['id'];
			$map['status'] = 1;
			$game[$k]['goods'] = Db::name('goods')
				->field('id,is_safe,title,area,server,cross,price,image')
				->where($map)
				->order('createtime desc')
				->limit(8)
				->select();
			foreach ($game[$k]['goods'] as $kk=>$vv) {
				$game[$k]['goods'][$kk]['image'] = config('api_image_url') . $vv['image'];
			}
		}
        // 交易记录
        $order = Db::name('order')
            ->field('account,game,title')
            ->where('status',5)
            ->order('ontime desc')
            ->limit(10)
            ->select();
        foreach ($order as $k=>$v) {
            $order[$k]['account'] = substr($v['account'],0,3). '****' . substr($v['account'],-4);
        }
		$res['hotGame'] = $hotGame;
		$res['ad'] = $ad;
		$res['game'] = $game;
		$res['article'] = $article;
		$res['popular'] = $popular;
		$res['order'] = $order;
		$this->success('ok',$res);
	}




	/**
	 * @ApiTitle    (app---买号)
	 * @ApiSummary  (app---买号)
	 * @ApiMethod   (POST)
	 * @ApiRoute    (api/Home/buyAccount)
	 * @ApiParams   (name="type", type="varchar", required=true, description="1 账号  2 金币  3 自抽号 4 装备")
     * @ApiParams   (name="game_type", type="varchar", required=false, description="network:端游 mobile:手游")
     * @ApiParams   (name="first", type="varchar", required=false, description="首字母")
	 * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
	 * @ApiReturn   ({
	"code": 1,
	"msg": "ok",
	"time": "1627553755",
	"data": {
		hotGame :   热门账号
		ad  :   banner图
		order   :   交易记录
		goodsList   :   游戏商品
	}
	 * })
	 */
	public function buyAccount()
	{
		$type = $this->request->post('type');
		$game_type = $this->request->post('game_type');
		$first = $this->request->post('first');
		if ($type == 1) {
			$typeName = '账号';
		} elseif ($type == 2) {
			$typeName = '游戏币';
		} elseif ($type == 3) {
			$typeName = '自抽号';
		} else {
			$typeName = '装备';
		}
		// banner图
		$ad = Db::name('ad')
			->field('id,aid,image,title,type')
			->where('aid',4)
			->where('status','normal')
			->select();
		foreach ($ad as $k=>$v) {
			$ad[$k]['image'] = config('api_image_url') . $v['image'];
		}
		// 热门账号
		$hotGame = Db::name('game_info')->field('id,game_id')->where('name',$typeName)->where('status','normal')->limit(8)->select();
		$games = [];
		foreach ($hotGame as $k=>$v) {
		    $hap['id'] = $v['game_id'];
            $hap['status'] = 'normal';
            $hap['is_hot'] = 1;
            if (!empty($first)) {
                $gap['first'] = $first;
            }
            if (!empty($game_type)) {
                $hap['type'] = $game_type;
            }
			$gms = Db::name('game')->field('id,game,image,type,first')->where($hap)->find();
            if (!empty($gms)) {
                $gms['image'] = config('api_image_url') . $gms['image'];
            }
			$games[] = $gms;
		}
		// 交易记录
		$order = Db::name('order')
			->field('account,game,title,amount')
			->where('order_class_type',$type)
			->where('status',5)
			->order('ontime desc')
			->limit(10)
			->select();
		foreach ($order as $k=>$v) {
			$order[$k]['account'] = substr($v['account'],0,3). '****' . substr($v['account'],-4);
		}
        // 游戏商品
        foreach ($hotGame as $k=>$v) {
            $gap['id'] = $v['game_id'];
            $gap['status'] = 'normal';
            $gap['is_hot'] = 1;
            if (!empty($game_type)) {
                $gap['type'] = $game_type;
            }
            if (!empty($first)) {
                $gap['first'] = $first;
            }
            $res['goodsList'][$k]['game'] = Db::name('game')->field('id,game')->where($gap)->find();
            $map['status'] = 1;
            $map['gameid'] = $res['goodsList'][$k]['game']['id'];
            $map['stock'] = ['gt',0];
            $map['goods_type'] = $v['id'];
            $res['goodsList'][$k]['list'] = Db::name('goods')
                ->field('id,is_safe,title,area,server,cross,price,image')
                ->where($map)
                ->order('createtime desc')
                ->limit(8)
                ->select();
            foreach ($res['goodsList'][$k]['list'] as $key=>$val) {
                $res['goodsList'][$k]['list'][$key]['image'] = config('api_image_url') . $val['image'];
            }
        }
        $res['hotGame'] = $games;
        $res['ad'] = $ad;
        $res['order'] = $order;
		$this->success('ok',$res);
	}


    /**
     * @ApiTitle    (app---即时通讯获取token)
     * @ApiSummary  (app---即时通讯获取token)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/getToken)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data": {
    token
    订单状态(1:待支付 2:待发货 3:已发货 4:交易中没用 5:已完成 6:已赔付 7:撤单 8:待审核 9:取消订单 11:待验证 12:待确认)
    }
     * })
     */
	public function getToken()
    {
        $token = $this->request->header('token');
        $this->is_login($token);
        $id = Db::name('personal')->where('token',$token)->value('id');
        $map['buyid'] = $id;
        $map['status'] = array('not in',array('1','6','7','8','9'));
        $res = Db::name('order')
            ->where($map)
            ->order('ontime desc')
            ->paginate(5,false,['query'=>request()->param()])
            ->each(function ($item,$key){
                //收货区服
                $item['role_server'] = Db::name('game_info')->where('id',$item['role_server'])->value('name');
                $admin = Db::name('admin')->where('id',$item['admin_id'])->find();
                $user = Db::name('personal')->where('id',$item['uid'])->find();
                $index = new Index();
                if ($user) {
                    $users = Db::name('personal')->where('id',$item['buyid'])->find();
                    //买家昵称
                    $item['othername'] = $users['nickname'];
                    $item['otheravatar'] = $users['avatar'];
                    $item['user'] = "买家";
                    $item['userToken'] = $index->getJt($users['id'],$users['account'],$users['avatar']);
                } else {
                    //卖家昵称
                    $item['othername'] = $user['nickname'];
                    $item['otheravatar'] = $user['avatar'];
                    $item['user'] = "卖家";
                    $item['userToken'] = $index->getJt($user['id'],$user['account'],$user['avatar']);
                }
                $item['adminToken'] = $index->getJt('admin'.$admin['id'],$admin['username'],$admin['avatar']);
                return $item;
            });
        $this->success('ok',$res);
    }



    /**
     * @ApiTitle    (app---用户设置)
     * @ApiSummary  (app---用户设置)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/userSet)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data": {
    paypass：支付密码  1：设置  0：未设置
    pass：登录密码  1：设置  0：未设置
    mobile：手机绑定  1：设置  0：未设置
    is_real：实名认证  1：设置  0：未设置

    }
     * })
     */
    public function userSet()
    {
        $token = $this->request->header('token');
        $this->is_login($token);
        $user = Db::name('personal')->field('id,paypass,pass,mobile,is_real')->where('token',$token)->find();
        if (empty($user['paypass'])) {
            $user['paypass'] = 0;
        } else {
            $user['paypass'] = 1;
        }
        if (empty($user['pass'])) {
            $user['pass'] = 0;
        } else {
            $user['pass'] = 1;
        }
        if (empty($user['mobile'])) {
            $user['mobile'] = 0;
        } else {
            $user['mobile'] = 1;
        }
        $this->success('ok',$user);
    }


    /**
     * @ApiTitle    (app---首页搜索商品)
     * @ApiSummary  (app---首页搜索商品)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/searchGoods)
     * @ApiParams   (name="keyword", type="varchar", required=false, description="关键字")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data": {
    "id": 1,
    "game": "游戏名",

     * })
     */
    public function searchGoods()
    {
        $keyword = $this->request->post('keyword');
        if (empty($keyword)) {
            $this->error('请输入关键字');
        }
        $map['gamename'] = array('like','%'.$keyword.'%');
        $map['status'] = 1;
        $res = Db::name('goods')
            ->field('id,goods_sn,uid,gamename,desc,image,images,kf_images,type_name,goods_type,title,price,plat,plat_id,operator,operator_id,area,area_id,server,server_id,cross,sku,info,stock,createtime,qq,mobile,is_warrant,is_appoint,jy_time,is_safe,is_pei,havetime,coin_ratio,coin,method')
            ->where($map)
            ->paginate(10,false,['query'=>request()->param()])
            ->each(function ($item,$key){
                $item['image'] = config('api_image_url') . $item['image'];
                return $item;
            });
        $this->success('ok',$res);
    }



    /**
     * @ApiTitle    (app---订单详情)
     * @ApiSummary  (app---订单详情)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/orderInfo)
     * @ApiParams   (name="id", type="varchar", required=false, description="订单id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data": {
    "id": 297,
    "order_sn": "20220213319076486314",
    "nickname": 昵称,
    "image": "https://780g.oss-cn-zhangjiakou.aliyuncs.comhttps://oss.dianjinghou.com/img/029/nocs/2021/05/28/1622196475997",
    "type_name": 物品类型,
    "title": 标题,
    "game": 游戏,
    "area": 区,
    "server": 服,
    "num": 购买数量,
    "amount": 价格,
    "ontime": 1641363211,
    "status": 1:待支付 2:待发货 3:已发货 4:交易中没用 5:已完成 6:已赔付 7:撤单 8:待审核 9:取消订单 11:待验证 12:待确认,
    "role": 收货角色,
    "role_server": 收货区服

     * })
     */
    public function orderInfo()
    {
        $id = $this->request->post('id');
        $res = Db::name('order')
            ->field('id,uid,order_sn,image,type_name,title,game,area,server,num,amount,ontime,status,role,role_server')
            ->where('id',$id)
            ->find();
        $res['nickname'] = Db::name('personal')->where('id',$res['uid'])->value('nickname');
        $res['image'] = config('api_image_url') . $res['image'];
        $this->success('ok',$res);
    }




    /**
     * @ApiTitle    (app---版本更新提醒)
     * @ApiSummary  (app---版本更新提醒)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/ver)
     * @ApiParams   (name="ver", type="varchar", required=false, description="版本号")
     * @ApiParams   (name="type", type="varchar", required=false, description="iOS/Android")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 0,
    "msg": "请更新新版本",
    "time": "1627553755",
    "data": null
     * })
     */
    public function ver()
    {
        $ver = $this->request->post('ver');
        $type = $this->request->post('type');
        $map['type'] = $type;
        $res = Db::name('ver')->where($map)->order('createtime desc')->limit(1)->find();
        if ($ver != $res['ver']) {
            $this->error('请更新新版本');
        }
    }




    /**
     * @ApiTitle    (app---转让协议获取信息)
     * @ApiSummary  (app---转让协议获取信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/mta)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 0,
    "msg": "请更新新版本",
    "time": "1627553755",
    "data": null
     * })
     */
    public function mta()
    {
        $token = $this->request->header('token');
        $this->is_login($token);
        $user = Db::name('personal')->field('mobile,name,id_card')->where('token',$token)->find();
        $this->success('ok',$user);
    }



    /**
     * @ApiTitle    (app---删除商品)
     * @ApiSummary  (app---删除商品)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/delGoods)
     * @ApiParams   (name="id", type="varchar", required=false, description="商品id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 0,
    "msg": "请更新新版本",
    "time": "1627553755",
    "data": null
     * })
     */
    public function delGoods()
    {
        $id = $this->request->post('id');
        $res = Db::name('goods')->where('id',$id)->update(['status'=>10]);
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }


    /**
     * @ApiTitle    (app---设置支付密码)
     * @ApiSummary  (app---设置支付密码)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/payPass)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="pass", type="varchar", required=false, description="密码")
     * @ApiParams   (name="password", type="varchar", required=false, description="确认密码")
     * @ApiParams   (name="mobile", type="varchar", required=false, description="手机号")
     * @ApiParams   (name="captcha", type="varchar", required=false, description="验证码")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 0,
    "msg": "请更新新版本",
    "time": "1627553755",
    "data": null
     * })
     */
    public function payPass()
    {
        $token = $this->request->header('token');
        $this->is_login($token);
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $pass = $this->request->post('pass');
        $password = $this->request->post('password');
        if (!Sms::check($mobile, $captcha, 'changepass')) {
            $this->error(__('请填写正确的验证码'));
        }
        if ($pass != $password) {
            $this->error('两次密码不一致');
        }
        $pay_pass = md5($pass);
        $res = Db::name('personal')->where('token',$token)->update(['paypass'=>$pay_pass]);
        if ($res) {
            $this->success('设置支付密码成功');
        } else {
            $this->error('设置支付密码失败');
        }
    }




    /**
     * @ApiTitle    (app---搜索订单)
     * @ApiSummary  (app---搜索订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/searchOrder)
     * @ApiParams   (name="keyword", type="varchar", required=false, description="关键字")
     * @ApiParams   (name="type", type="varchar", required=false, description="buyid：买家 uid：卖家")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data": {
    "id": 1,
    "game": "游戏名",

     * })
     */
    public function searchOrder()
    {
        $token = $this->request->header('token');
        $type = $this->request->post('type');
        $keyword = $this->request->post('keyword');
        $this->is_login($token);
        $id = Db::name('personal')->where('token',$token)->value('id');
        if (empty($keyword)) {
            $this->error('请输入关键字');
        }
        $map['title'] = array('like','%'.$keyword.'%');
        $map['status'] = array('not in',array('4'));;
        $map[$type] = $id;
        $res = Db::name('order')
            ->field('id,order_sn,goods_id,game_id,image,price,type_name,buy_type,title,game,area,server,num,amount,ontime,status,reason,complaint,admin_id,uid,buyid')
            ->where($map)
            ->paginate(10,false,['query'=>request()->param()])
            ->each(function ($item,$key){
                $user = Db::name('personal')->where('id',$item['uid'])->find();
                $admin = Db::name('admin')->where('id',$item['admin_id'])->find();
                $index = new Index();
                if ($user) {
                    $users = Db::name('personal')->where('id',$item['buyid'])->find();
                    //买家昵称
                    $item['othername'] = $users['nickname'];
                    $item['otheravatar'] = $users['avatar'];
                    $item['user'] = "买家";
                    $item['userToken'] = $index->getJt($users['id'],$users['account'],$users['avatar']);
                } else {
                    //卖家昵称
                    $item['othername'] = $user['nickname'];
                    $item['otheravatar'] = $user['avatar'];
                    $item['user'] = "卖家";
                    $item['userToken'] = $index->getJt($user['id'],$user['account'],$user['avatar']);
                }
                $item['image'] = config('api_image_url') . $item['image'];
                $item['adminToken'] = $index->getJt('admin'.$admin['id'],$admin['username'],$admin['avatar']);
                return $item;
            });
        $this->success('ok',$res);
    }




    /**
     * @ApiTitle    (app---收藏搜索)
     * @ApiSummary  (app---收藏搜索)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Home/collectionSearch)
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data": {
    "id": 21,
    "game": 游戏名,
    "goods_type": [
    {
    类型
    "id": 1810,
    "name": "装备"
    }
    ],
    "server": [
    {
    区服
    "id": 1798,
    "name": "1区"
    },
    ]
    },

     * })
     */
    public function collectionSearch()
    {
        $res['game'] = Db::name('game')->field('id,game')->where('status','normal')->select();
        foreach ($res['game'] as $k=>$v) {
            $res['game'][$k]['goods_type'] = Db::name('game_info')->field('id,name')->where('game_id',$v['id'])->where('gt_id',5)->select();
            $res['game'][$k]['server'] = Db::name('game_info')->field('id,name')->where('game_id',$v['id'])->where('gt_id',3)->select();
        }
        $this->success('ok',$res);
    }

}
